package com.jiang.listener;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author Administrator
 * @监听器(主要是为了后面可以做在线人数统计功能)
 *                          <li>监听服务器启动</li>
 *                          <li>监听Session属性值增加</li>
 *                          <li>监听Session销毁</li>
 *                          <li>在线人数统计放在Application中</li>
 */
public class HRContextListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
	// 全局共享的内置对象
	private ServletContext sc = null;

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("web容器启动, SevletContext中加载在线用户容器");
		this.sc = sce.getServletContext();
		sce.getServletContext().setAttribute("allUsers", new HashSet<String>());
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("web容器销毁");
		this.sc = null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		// 获取的增加的属性名称
		String sessionAttrName = event.getName();
		// 如果是新用户成功登录后，肯定要保存该用户在Session中以方便后面的每次过滤器查看
		if ("uid".equalsIgnoreCase(sessionAttrName)) {
			Set<String> all = (Set<String>) this.sc.getAttribute("allUsers");
			all.add(event.getValue().toString());
		}
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {

	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {

	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		// 肯定是先做监听器创建session 然后再过滤器 再拦截器
	}

	@SuppressWarnings("unchecked")
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		// 用户注销或者延迟时间到达销毁Session
		// 这里要删除该在线用户
		HttpSession session = se.getSession();
		if (session.getAttribute("uid") != null) {
			String uid = (String) session.getAttribute("uid");
			Set<String> allUsers = (Set<String>) sc.getAttribute("allUsers");
			allUsers.remove(uid);
		}

	}

}
